package com.stylefeng.guns.modular.yjya.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.persistence.dao.AccidentTypeMapper;
import com.stylefeng.guns.common.persistence.model.AccidentType;
import com.stylefeng.guns.common.persistence.model.CounterplanTemplate;
import com.stylefeng.guns.common.persistence.model.CounterplanTypeTemplate;
import com.stylefeng.guns.common.persistence.model.Roadnet;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.modular.roadnet.service.IRoadnetService;
import com.stylefeng.guns.modular.yjya.dao.CounterplanTemplateDao;
import com.stylefeng.guns.modular.yjya.service.IAccidentTypeService;
import com.stylefeng.guns.modular.yjya.service.ICounterplanTemplateService;
import com.stylefeng.guns.modular.yjya.service.ICounterplanTypeTemplateService;
import com.stylefeng.guns.modular.yjya.warpper.CounterplanTemplateWarpper;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 预案模板控制器
 *
 * @author xuziyang
 * @Date 2018-01-04 11:01:44
 */
@Controller
@RequestMapping("/counterplanTemplate")
public class CounterplanTemplateController extends BaseController {

    private String PREFIX = "/yjya/counterplanTemplate/";

    @Autowired
    private ICounterplanTemplateService counterplanTemplateService;

    @Autowired
    private CounterplanTemplateDao counterplanTemplateDao;

    @Autowired
    private IRoadnetService roadnetService;

    @Autowired
    private IAccidentTypeService accidentTypeService;

    @Autowired
    private AccidentTypeMapper accidentTypeMapper;

    @Autowired
    private ICounterplanTypeTemplateService counterplanTypeTemplateService;



    /**
     * 跳转到预案模板首页
     */
    @RequestMapping("")
    public String index(Model model) {
        List<CounterplanTypeTemplate> counterplanTypeTemplateList = counterplanTypeTemplateService.selectList(null);
        model.addAttribute("counterplantypes",counterplanTypeTemplateList);
        return PREFIX + "counterplanTemplate.html";
    }

    /**
     * 跳转到添加预案模板
     */
    @RequestMapping("/counterplanTemplate_add")
    public String counterplanTemplateAdd(Model model) {
        List<CounterplanTypeTemplate> counterplanTypeTemplateList = counterplanTypeTemplateService.selectList(null);
        model.addAttribute("counterplantypes",counterplanTypeTemplateList);
        return PREFIX + "counterplanTemplate_add.html";
    }

    /**
     * 跳转到修改预案模板
     */
    @RequestMapping("/counterplanTemplate_update/{counterplanTemplateId}")
    public String counterplanTemplateUpdate(@PathVariable Integer counterplanTemplateId, Model model) {
        CounterplanTemplate counterplanTemplate = counterplanTemplateService.selectById(counterplanTemplateId);
        if(counterplanTemplate.getStationId()!=null){
            Integer lineId =null;
            String stationIds = counterplanTemplate.getStationId();
            List<Integer> stationIdList = new ArrayList(Arrays.asList(stationIds.split(",")));
            List<Roadnet> roadnetList = new ArrayList<>();
            String stationName = "";
            for(int i=0;i<stationIdList.size();i++){
                Roadnet station = roadnetService.selectById(stationIdList.get(i));
                roadnetList.add(station);
            }
            for(int i=0;i<roadnetList.size();i++){
                if(i==roadnetList.size()-1){
                    stationName += roadnetList.get(i).getName();
                    lineId = roadnetList.get(i).getPid();
                }
                else{
                    stationName += roadnetList.get(i).getName()+">>";
                }
            }
            Roadnet line =roadnetService.selectById(lineId);
            //选中的车站数量
            model.addAttribute("checkCount",stationIdList.size());
            model.addAttribute("stationName",line.getName()+":"+stationName);
        }
        else{
            model.addAttribute("stationName",null);
        }

        if (counterplanTemplate.getAccidentTypeId() != null) {
           AccidentType accidentType =  accidentTypeService.selectById(counterplanTemplate.getAccidentTypeId());
            if (accidentType != null) {
                String pids = accidentType.getPids();
                List<String> ids = new ArrayList<>(Arrays.asList(pids.split("/")));
                ids.add(String.valueOf(accidentType.getId()));
                List<AccidentType> accidentTypeList =  accidentTypeMapper.selectBatchIds(ids);
                String accideentTypeName = "";
                for(int i=1;i<accidentTypeList.size();i++){
                    accideentTypeName += accidentTypeList.get(i).getName()+"--";
                }

                model.addAttribute("accidentTypeName", accideentTypeName+accidentTypeList.get(0).getName());
            }
        }

        model.addAttribute("item",counterplanTemplate);
        List<CounterplanTypeTemplate> counterplanTypeTemplateList = counterplanTypeTemplateService.selectList(null);
        model.addAttribute("counterplantypes",counterplanTypeTemplateList);
        LogObjectHolder.me().set(counterplanTemplate);
        return PREFIX + "counterplanTemplate_edit.html";
    }

    /**
     * 获取预案模板列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(value = "name",required = false)String name
            ,@RequestParam(value = "type",required = false) String type
            ,@RequestParam(value = "level",required = false) String level
            ,@RequestParam(value = "accidentTypeId",required = false) Integer accidentTypeId) {
        Page<CounterplanTemplate> page = new PageFactory<CounterplanTemplate>().defaultPage();
        List<Map<String, Object>> result = counterplanTemplateDao.getCounterplanTemplates(page, name, type, level,accidentTypeId);
        page.setRecords((List<CounterplanTemplate>) new CounterplanTemplateWarpper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 弹出预案模板匹配页面
     */
    @RequestMapping("/counterplan_template_mate_index")
    public Object contactSelIndex(String type
            , String level
            ,Integer accidentTypeId,Model model) {
        model.addAttribute("type",type);
        model.addAttribute("level",level);
        model.addAttribute("accidentTypeId",accidentTypeId);
        return PREFIX + "counterplan_template_mate.html";
    }

    /**
     * 编制预案是匹配的预案模板列表
     */
    @RequestMapping(value = "/counterplan_template_mate")
    @ResponseBody
    public Object counterplanTemplateMate(@RequestParam(value = "name",required = false)String name
            ,@RequestParam(value = "type",required = false) String type
            ,@RequestParam(value = "level",required = false) String level
            ,@RequestParam(value = "accidentTypeId",required = false) Integer accidentTypeId) {
        Page<CounterplanTemplate> page = new PageFactory<CounterplanTemplate>().defaultPage();
        List<Map<String, Object>> result = counterplanTemplateDao.getCounterplanTemplates(page, name, type, level,accidentTypeId);
        page.setRecords((List<CounterplanTemplate>) new CounterplanTemplateWarpper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 选择某个预案模板
     */
    @RequestMapping(value = "/counterplanTemplateId")
    @ResponseBody
    public Object counterplanTemplateId(@RequestParam Integer id) {
        CounterplanTemplate counterplanTemplate = counterplanTemplateService.selectById(id);
        return counterplanTemplate;
    }

    /**
     * 新增预案模板
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(CounterplanTemplate counterplanTemplate) {
        counterplanTemplateService.insert(counterplanTemplate);
        return counterplanTemplate;
    }

    /**
     * 删除预案模板
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam(value = "ids[]") List<Integer> ids) {
        counterplanTemplateService.deleteBatchIds(ids);
        return SUCCESS_TIP;
    }

    /**
     * 删除预案模板
     */
    @RequestMapping(value = "/deleteTemporary")
    @ResponseBody
    public Object delete(@RequestParam(value = "id") Integer id) {
        counterplanTemplateService.deleteById(id);
        return SUCCESS_TIP;
    }

    /**
     * 修改提交时删除旧的预案模板
     * */
    @RequestMapping(value = "/deleteTemporary/{temprraryId}")
    @ResponseBody
    public Object deleteOld(@RequestParam(value = "id") Integer id,@PathVariable Integer temprraryId) {
        counterplanTemplateService.deleteById(id);
        CounterplanTemplate counterplanTemplate = counterplanTemplateService.selectById(temprraryId);
        
        return SUCCESS_TIP;
    }

    /**
     * 修改预案模板
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(CounterplanTemplate counterplanTemplate) {
        counterplanTemplateService.updateById(counterplanTemplate);
        return super.SUCCESS_TIP;
    }

    /**
     * 预案模板详情
     */
    @RequestMapping(value = "/detail/{counterplanTemplateId}")
    public Object detail(@PathVariable("counterplanTemplateId") Integer counterplanTemplateId, Model model) {
        CounterplanTemplate template = counterplanTemplateService.selectById(counterplanTemplateId);
        if (template == null) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        Map<String, Object> templateMap = BeanKit.beanToMap(template);
        model.addAttribute("template", new CounterplanTemplateWarpper(templateMap).warp());
        return PREFIX + "counterplanTemplate_detail.html";
    }

    /**
     * 编制预案
     */
    @RequestMapping(value = "/compile/{counterplanTemplateId}")
    public Object compile(@PathVariable("counterplanTemplateId") Integer counterplanTemplateId, Model model) {
        CounterplanTemplate counterplanTemplate = counterplanTemplateService.selectById(counterplanTemplateId);
        if(counterplanTemplate.getStationId()!=null){
            Roadnet station = roadnetService.selectById(counterplanTemplate.getStationId());
            model.addAttribute("stationName",station.getName());
        }
        else{
            model.addAttribute("stationName",null);
        }
        model.addAttribute("item",counterplanTemplate);
        LogObjectHolder.me().set(counterplanTemplate);
        return PREFIX + "counterplane_compile.html";
    }


    /**
     * 预案导入
     * @param multipartHttpServletRequest
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.POST,path = "/counterplateTemplateExport")
    @ResponseBody
    public Object counterplateTemplateExport(MultipartHttpServletRequest multipartHttpServletRequest, Model model)throws Exception{

        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        InputStream inputStream = null;
        for(Map.Entry<String,MultipartFile> entity : fileMap.entrySet()){
            MultipartFile multipartFile = entity.getValue(); //获取上传文件对象
            inputStream = multipartFile.getInputStream();
        }
        String content = "";
        XWPFDocument document = new XWPFDocument(inputStream);
        XHTMLOptions options = XHTMLOptions.create().indent(4);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(document, baos, options);
        baos.close();
        content =new String(baos.toByteArray());
        //替换UEditor无法识别的转义字符
        String htmlContent1=content.replaceAll("&ldquo;","\"").replaceAll("&rdquo;","\"").replaceAll("&mdash;","-");
        return htmlContent1;

    }

    /**
     * 获取ueditor配置文件
     */
    @RequestMapping(value="/config")
    public void config(HttpServletRequest request,HttpServletResponse response){
        try{
            response.setContentType("application/json");
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type","text/html");
            String rootPath = request.getSession().getServletContext().getRealPath("/");
//            String exec = new ActionEnter(request,rootPath).exec();
        }
        catch(Exception e){

        }
    }
}
